import {
  BatchBindTagClassReq,
  OptionTagReq,
} from '@/api/premium/content/model/tagModel'
import {
  batchBindCategory,
  optionTag,
  TagApi,
} from '@/api/premium/content/tag'
import { useStore } from '@/store'
import { message } from 'ant-design-vue'
import { computed, reactive } from 'vue'
import { AddTagDiaState } from '../types'

const useAddTagDialog = (searchApi: AsyncFun) => {
  const store = useStore()
  const addTagDiaState = reactive<AddTagDiaState>({
    visiable: false,
    formData: {
      tagName: '',
      categoryIds: [],
    },
  })

  const openAddTagDia = () => {
    addTagDiaState.visiable = true
  }

  const confirmAddTagDia = async () => {
    // 添加标签
    const addTagReqData: OptionTagReq = {
      tagName: addTagDiaState.formData.tagName,
    }
    const { data } = await optionTag(addTagReqData)

    // 绑定标签
    const categoryList = addTagDiaState.formData.categoryIds.map(
      (item) => item.value
    )
    if (!categoryList.includes('-1')) {
      const bindCategoryReqData: BatchBindTagClassReq = {
        categoryList,
        relationList: [data.id],
      }
      await batchBindCategory(bindCategoryReqData)
    }
    message.success('添加标签成功！')
    addTagDiaState.visiable = false
    await searchApi()
  }
  const batchBindCategoryLoading = computed(() =>
    store.getters['global/isOpLoading'](TagApi.BATCH_BIND_TAG_CLASS)
  )
  const optionTagLoading = computed(() =>
    store.getters['global/isOpLoading'](TagApi.OPTION_TAG)
  )

  return {
    addTagDiaState,
    openAddTagDia,
    confirmAddTagDia,
    batchBindCategoryLoading,
    optionTagLoading,
  }
}

export default useAddTagDialog
